<template>
  <div id="questionsView">
    <a-form :model="searchParams" layout="inline">
      <!-- <a-form-item field="tags" label="标签" style="min-width: 240px">
        <a-input-tag :style="{ width: '240px' }" v-model="searchParams.tags" placeholder="请输入标签" />
      </a-form-item> -->
      <a-form-item field="tags" label="标签">
        <a-select v-model="searchParams.tags" :style="{width:'240px'}" placeholder="请选择标签" multiple allow-search :max-tag-count="4" >
          <a-option v-for="item of tagsList" :value="item.id" :label="item.text" />
        </a-select>
      </a-form-item>
      <a-form-item field="difficulty" label="难度" >
        <a-select v-model="searchParams.difficulty" :style="{width:'120px'}" placeholder="请选择难度" allow-clear default-value="">
          <a-option v-for="item of difficultyList" :value="item.value" :label="item.text" />
        </a-select>
      </a-form-item>
      <a-form-item field="" label="时间" style="min-width: 240px">
        <a-range-picker @change="onChange" style="width: 240px; margin-right: 24px; margin-bottom: 24px;"/>
      </a-form-item>
      <a-form-item field="title" label="名称" style="min-width: 240px">
        <a-input :style="{ width: '240px' }" v-model="searchParams.title" placeholder="搜索题目名称、编号" />
      </a-form-item>
      <a-button v-if="isAdmin==1" style="text-align: right;" type="primary" @click="toCreateQuestion()">新增题目</a-button>
    </a-form>
    
    <!-- <a-divider size="0" /> -->
    <a-table :ref="tableRef" :columns="columns" :data="dataList" column-resizable :pagination="{
      pageSize: searchParams.pageSize,
      current: searchParams.current,
    }" @page-change="onPageChange">
      <template #title = "{record}">
        <a-link v-on:click="toQuestionPage(record.id)" :hoverable="true">
          {{ record.title }}
        </a-link>
      </template>
      <template #tagsText="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tagsText" :key="index" color="green">{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #difficultyText = "{record}">
        <a-tag style="font-weight: bolder" :style="{color: getColor(record.difficulty)}" size="large">{{ record.difficultyText }}</a-tag>
      </template>
      <template #acceptedRate="{ record }">
        {{
          `${record.submitNum ? (record.acceptedNum * 100 / record.submitNum).toFixed(2) : "0"} % (${record.acceptedNum}/${record.submitNum})`
        }}
      </template>
      <template #createTime="{ record }">
        <!-- {{ moment(record.createTime).format("YYYY-MM-DD") }} -->
        {{ record.createTime }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button v-if="record.hasAnswer==0 && isAdmin==1" type="primary" @click="createAnswer(record.id)">发布题解</a-button>
          <a-button v-if="record.hasAnswer==1 && isAdmin==1" type="primary" @click="updateAnswer(record.id)">修改题解</a-button>
          <a-button v-if="isAdmin==1" type="primary" @click="doUpdate(record.id)">修改</a-button>
          <a-button v-if="isAdmin==1" status="danger" @click="doDelete(record.id)">删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  QuestionVO,
  QuestionControllerService,
  QuestionQueryRequest,
  CommonControllerService
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import ACCESS_ENUM from "@/access/accessEnum";

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);
const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  difficulty: undefined,
  startTime: "",
  endTime: "",
  userId: undefined,
  pageSize: 6,
  current: 1,
});

let difficultyList = ref(
  "" as any
);

let tagsList = ref(
  "" as any
)
const router = useRouter();
const isAdmin = ref();
const store = useStore();

const loadData = async () => {
  searchParams.value.userId = store.state.user.loginUser?.id
  const res = await QuestionControllerService.listPageQuestionVoUsingPost(
      {
      ...searchParams.value,
      sortField: "createTime",
      sortOrder: "descend",
      }
  );
      console.log("res",res.data);
      
  const res2 = await CommonControllerService.getEnumsListUsingGet('题目难度');
  difficultyList.value = res2.data

  const res3 = await CommonControllerService.getOptionsListUsingGet('题目标签');
  tagsList.value = res3.data

  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
  if(store.state.user.loginUser?.userRole == ACCESS_ENUM.ADMIN){
    isAdmin.value = 1
  }
};

const onChange = (dateString: any, datea: any) => {
  if(dateString){
    searchParams.value.startTime = dateString[0];
    searchParams.value.endTime = dateString[1];
  }else{
    searchParams.value.startTime = "";
    searchParams.value.endTime = "";
  }
}

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const columns = [
  {
    title: "编号",
    dataIndex: "code",
    width: 60,
  },
  {
    title: "题目名称",
    slotName: "title",
    width: 240,
  },
  {
    title: "标签",
    slotName: "tagsText",
    width: 240,
  },
  {
    title: "难度",
    slotName: "difficultyText",
    width: 120,
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
    width: 180,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 180,
  },
  {
    slotName: "optional",
    width: 120,
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const getColor = (status:number) => {
  switch(status){
    case 1:
      return "green";
    case 2:
      return "blue";
    case 3:
      return "red";
  }
}

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (id: number) => {
  router.push({
    path: `/view/question/${id}`,
  });
};

const doDelete = async (id: number) => {
  var isTrue = confirm("确定要删除吗？")
  if(!isTrue){
    return;
  }
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};

const toCreateQuestion = () => {
  router.push({
    path: "/add/question",
  });
}

const doUpdate = (id: number) => {
  router.push({
    path: `/update/question/${id}`,
  });
};

/**
 * 发布题解
 */
 const createAnswer = (questionId:number) => {
  router.push({
    path: `/create/answer/${questionId}`,
  });
}

/**
 * 修改题解
 */
 const updateAnswer = (questionId:number) => {
  router.push({
    path: `/update/answer/${questionId}`,
  });
}

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>

<style scoped>
#questionsView {
  max-width: 1280px;
  margin: 0 auto;
}
</style>
